package com.example.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.ReentrantLock;

@Service
@Slf4j
public class ReentrantLockExampleService {

    private final ReentrantLock lock = new ReentrantLock();

    public void executeCriticalTask() {
        log.info("线程 {} 尝试第一次获取锁", Thread.currentThread().getName());
        lock.lock();
        try {
            log.info("线程 {} 成功获取第一次锁", Thread.currentThread().getName());

            // 模拟临界区任务
            performSubTask();

            log.info("线程 {} 执行临界任务完成", Thread.currentThread().getName());
        } finally {
            log.info("线程 {} 释放第一次锁", Thread.currentThread().getName());
            lock.unlock();
        }
    }

    private void performSubTask() {
        log.info("线程 {} 尝试第二次获取锁（可重入）", Thread.currentThread().getName());
        lock.lock();  // 再次获取同一把锁（可重入）
        try {
            log.info("线程 {} 成功获取第二次锁（可重入）", Thread.currentThread().getName());
            // 模拟第二个临界区任务
            Thread.sleep(1000);
            log.info("线程 {} 完成子任务", Thread.currentThread().getName());
        } catch (InterruptedException e) {
            log.error("线程 {} 被中断", Thread.currentThread().getName(), e);
        } finally {
            log.info("线程 {} 释放第二次锁（可重入）", Thread.currentThread().getName());
            lock.unlock();
        }
    }
}
